package sever

import (
	"context"
	"fmt"
	hotel "hotel_3.27/common/proto"
	"hotel_3.27/rpc/model"
	"hotel_3.27/variable"
	"math/rand"
	"time"
)

func SendSms(in *hotel.SendSmsReq) (*hotel.SendSmsResp, error) {
	code := rand.Intn(9000) + 1000

	//sms, err := pkg.SendSms(in.Mobile, strconv.Itoa(code))
	//if err != nil {
	//	return nil, err
	//}
	//if *sms.Body.Code != "ok" {
	//	return nil, fmt.Errorf(*sms.Body.Message)
	//}
	//
	variable.Client.Set(context.Background(), "SendSms"+in.Source+in.Mobile, code, time.Minute*2)

	return &hotel.SendSmsResp{Success: true}, nil
}
func Login(in *hotel.LoginReq) (*hotel.LoginResp, error) {
	u := model.User{}

	get := variable.Client.Get(context.Background(), "SendSmslogin"+in.Mobile)

	if get.Val() != in.Code {
		return nil, fmt.Errorf("登录失败,验证码错误")
	}

	mobile, err := u.GetUserMobile(in.Mobile)
	if err != nil {
		return nil, err
	}
	if mobile == nil {
		return nil, fmt.Errorf("该用户还未注册")
	}

	return &hotel.LoginResp{UserId: int64(mobile.ID)}, nil
}
func OrderAdd(in *hotel.OrderAddReq) (*hotel.OrderAddResp, error) {
	m := model.Hotel{}
	o := model.Order{}
	Hotel, _ := m.FindHotelId(in.HotelId)
	if Hotel == nil {
		return nil, fmt.Errorf("酒店不存在")
	}

	if in.Sum > Hotel.Stock {
		return nil, fmt.Errorf("库存不足")
	}

	_, err := o.CreateHotel(in)
	if err != nil {
		return nil, fmt.Errorf("订单生成失败")
	}

	return &hotel.OrderAddResp{Success: true}, nil
}
func OrderList(in *hotel.OrderListReq) (*hotel.OrderListResp, error) {
	o := model.Order{}
	Hotel, err := o.FindHotel()
	if err != nil {
		return nil, fmt.Errorf("订单列表展示失败")
	}
	var All []*hotel.OrderList

	for _, i := range Hotel {
		All = append(All, &hotel.OrderList{
			OrderId: int64(i.ID),
			HotelId: i.HotelId,
			UserId:  i.UserId,
			OrderSn: i.OrderSn,
			Num:     i.Num,
			Price:   float32(i.Price),
			Pay:     i.Pay,
			Status:  i.Status,
		})
	}
	return &hotel.OrderListResp{
		List: All,
	}, nil

}
